package com.mojo.concurrent.concurrent_05_util;

import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * 信号标并发工具类示例
 * <p>
 * 同一时间控制并发数
 * </p>
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/20 10:30
 */
public class SemaphoreDemo1 {
    public static void main(String[] args) {
        semaphoreCounter counter = new semaphoreCounter();
        IntStream.range(0, 10000).parallel().forEach(i -> counter.incrAndGet());
        System.out.println(counter.getNum());
    }

    static class semaphoreCounter {
        int num;
        private Semaphore writeSemaphore = new Semaphore(1);
        private Semaphore readSemaphore = new Semaphore(100, true);

        public int incrAndGet() {
            try {
                writeSemaphore.acquireUninterruptibly();
                return num++;
            } finally {
                writeSemaphore.release();
            }
        }

        public int getNum() {
            try {
                readSemaphore.acquireUninterruptibly();
                return num;
            } finally {
                readSemaphore.release();
            }
        }
    }
}
